package Java并发编程艺术第一章;

public class DeadLockDemo {


    //A,B两个锁对象
    private static String A = "A";
    private static String B = "B";

    public static void main(String[] args) {
        DeadLockDemo.deadLock();
    }

    public static void  deadLock(){
        //创建线程1
        Thread t1 = new Thread(()->{
            //此时A要等待B释放锁
            synchronized(A){
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //此时B要等待A加锁
                synchronized (B){
                    System.out.println("1");
                }
            }
        });
        //创建线程2
        Thread t2 = new Thread(()->{
            //先对B加锁,在对A加锁
            //此时B要等待A
           synchronized(B){
               synchronized(A){
                   //此时A要等待B加锁
                   System.out.println("2");
               }
           }
        });

        t1.start();
        t2.start();

    }









//    private static String A = "A";
//    private static String B = "B";
//    public static void main(String[] args) {
//        new DeadLockDemo().deadLock();
//    }
//    private void deadLock() {
//        Thread t1 = new Thread(new Runnable() {
//            @Override
//            public void run() {
//                synchronized (A) {
//                    try {
//                        Thread.currentThread().sleep(2000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    synchronized (B) {
//                        System.out.println("1");
//                    }
//                }
//            }
//        });
//        Thread t2 = new Thread(new Runnable() {
//            @Override
//            public void run() {
//                synchronized (B) {
//                    synchronized (A) {
//                        System.out.println("2");
//                    }
//                }
//            }
//        });
//        t1.start();
//        t2.start();
//    }

}